<template>
    <div class="lock">
        <Tabs type="card" :animated="false" :value="selectedName" @on-click="changeTab">
            <TabPane label="门锁信息" name="one"  id="padding15">
                <Card class="lock-base" dis-hover :padding='0' v-if="selectedName == 'one'">
                    <p slot='title'>
                        基本信息
                    </p>
                    <div slot="extra" v-if="canUseEleUnlock">
                        <i-button
                            v-if="!room.rsvlock_config || room.rsvlock_config.status === 2"
                            :loading="setting"
                            @click="handleEleLock('open')">
                            开启电子反锁
                        </i-button>
                        <i-button
                            v-if="(!room.rsvlock_config || room.rsvlock_config.status === 1) && room.is_public_room"
                            :loading="setting"
                            @click="handleEleLock('close')">
                            禁止电子反锁
                        </i-button>
                    </div>
                    <Row class='lock-base-row' type="flex">
                        <Col span='8' class='lock-base-row-item'>
                            <Row type='flex' align='middle' class='lock-base-row-item-line'>
                                <strong>基本信息</strong>
                                <Button type="primary" @click="handleSearch(room)" style="margin-left:20px"> 刷新</Button>
                            </Row>
                            <Row class='lock-base-row-item-line'>
                                <i>名称：</i>
                                <Input style='width:50%' v-model='room.description' :readonly='edit'></Input>
                                <Button type='ghost' class="margin-left-10 yd-button" v-show='edit==true' @click='edit=!edit' v-pmis="23">修改</Button>
                                <Button class=" margin-left-10 yd-button" v-show='edit==false' @click='ok'>保存</Button>
                            </Row>
                            <Row class='lock-base-row-item-line'>
                                <i>序列号:</i>
                                {{room.sn}}
                            </Row>
                            <Row class='lock-base-row-item-line'>
                                <i>uuid：</i>
                                {{room.uuid}}
                            </Row>
                            <Row class='lock-base-row-item-line' v-if="room.lqi >= 0">
                                <i>信号强度:</i>
                                {{room.lqi}}（更新时间：{{room.lqi_refreshtime | dateFrm}}）
                            </Row>
                            <Row class='lock-base-row-item-line' v-if="canUseEleUnlock">
                                <strong>电子反锁启动状态:</strong>
                                {{room.rsvlock_config && room.rsvlock_config.status | enableEleLockStatus}}
                            </Row>
                            <Row class='lock-base-row-item-line' v-if="room.locker_status && canUseEleUnlock">
                                <strong>电子反锁:</strong>
                                {{room.locker_status.ele_rvslock ? '已反锁' : '未反锁'}}（更新时间：{{room.locker_status.ele_rvslock_refreshtime | dateFrm}}）
                            </Row>
                            <Row class='lock-base-row-item-line'>
                                <i>状态：</i>
                                <span class="margin-right-10">{{room.onoff_line == 1?'在线':'离线'}}</span>（更新时间:{{room.onoff_time | dateFrm}}）
                            </Row>
                            <Row class='lock-base-row-item-line'>
                                <i>电量：</i>
                                <span class="margin-right-10">{{room.power}}（更新时间：{{room.power_refreshtime | dateFrm}}）</span>
                            </Row>
                            <Row class='lock-base-row-item-line'>
                                <i>型号：</i>
                                {{room.type || '-'}}
                            </Row>
                            <Row class='lock-base-row-item-line'>
                                <i>绑定网关:</i>
                                {{room.gateway_description}}
                            </Row>
                        </Col>
                        <Col span='8' class='lock-base-row-item'>
                            <Row type='flex' align='middle' class='lock-base-row-item-line'>
                                <strong>保修信息</strong>
                            </Row>
                            <Row class='lock-base-row-item-line'>
                                <strong>绑定时间：</strong>
                                {{room.bind_time | dateFrm}}
                            </Row>
                            <Row class='lock-base-row-item-line'>
                                <strong>保修起始时间：</strong>
                                {{room.guarantee_begin}}
                            </Row>
                            <Row class='lock-base-row-item-line'>
                                <strong>保修截止时间：</strong>
                                {{room.guarantee_end}}
                            </Row>

                            <br>
                            <Row type='flex' align='middle' class='lock-base-row-item-line'>
                                <strong>硬件信息</strong>
                            </Row>
                            <Row v-if="key!='versions'" :key="key" class='lock-base-row-item-line' v-for="(item,key) in room.hardware_info">
                                <strong>{{key}}：</strong>
                                <span>{{item}}</span>
                            </Row>
                        </Col>
                        <Col span='8' class='lock-base-row-item' style='border-right:none' v-if="room.hardware_info && room.hardware_info.versions">
                            <Row type='flex' align='middle' class='lock-base-row-item-line'>
                                <strong>硬件版本</strong>
                            </Row>

                            <Row class='lock-base-row-item-line' :key="versionsKey" v-for="(versionsItem,versionsKey) in room.hardware_info.versions" v-if="versionMap[versionsKey]">
                                <strong>{{versionMap[versionsKey]}}：</strong>
                                <span>{{versionsItem}}</span>
                            </Row>
                        </Col>
                    </Row>
                </Card>
            </TabPane>

            <TabPane label="授权记录" name="two" v-if="permissions['device_control']"  id="padding15">
                <roomLicens :lockDetail="room" :operateType="'lock'" v-if="selectedName == 'two'"></roomLicens>
            </TabPane>

            <TabPane label="开关记录" name="three" id="padding15">
                <Row v-if="selectedName == 'three'">
                <Row :gutter='16' style="padding:0 20px">
                    <Col span='7'>
                        <Select style='width:100%' v-model='data_slot' @on-change='period'>
                            <Option value='0'>最近三天</Option>
                            <Option value='1'>最近七天</Option>
                            <Option value='2'>最近一个月</Option>
                            <Option value='3'>自定义</Option>
                        </Select>
                    </Col>
                    <Col span='7'>
                        <DatePicker type="date" placeholder="Select date" style="width: 100%" v-model='listQuery.start_time'></DatePicker>
                    </Col>
                    <Col span='7'>
                        <DatePicker type="date" placeholder="Select date" style="width: 100%" v-model='listQuery.end_time'></DatePicker>
                    </Col>
                    <Col span='3'>
                        <Button type='primary' style='width:100%' @click='getOpenList'>搜索</Button>
                    </Col>
                </Row>
                <Table stripe border :columns="openLogColumns" :data="dataLockLog" :loading="loadingLog" size="small" class='margin-top-20'></Table>
                <Page :total="total" :page-size="listQuery.limit" :current='listQuery.page' show-elevator show-total style="text-align:center" class='margin-top-10' @on-change='getOpenList'></Page>
                </Row>
            </TabPane>

            <TabPane label="操作记录" name="four"  id="padding15">
                <roomOperate :room="room" :operateType="'lock'" v-if="selectedName == 'four'"></roomOperate>
            </TabPane>

            <TabPane label="异常记录" name="five"  id="padding15">
                <roomUnnormal :room="room" :unnormalType="'LOCK'" v-if="selectedName == 'five'"></roomUnnormal>
            </TabPane>

            <TabPane label="功能码" name="six" v-if="isD3OrT3Lock">
                <functionCode v-if="selectedName === 'six'" :lockInfo="deviceInfo" :specificModel="specificModel"></functionCode>
            </TabPane>

            <TabPane label="第三方接口调用记录" name="openapi-log">
                <openapi-log v-if="loadedComponent.includes('openapi-log')" device-type="lock" :device-id="deviceInfo.id" :room-id="deviceInfo.roomId"></openapi-log>
            </TabPane>
        </Tabs>
    </div>
</template>
<script>
// import util from '@/libs/util';
import debounce from 'lodash/debounce'
import { refreshRoom } from './room-list/util'
import { http, api } from '@/libs/http'
import util from '@/libs/util'
import { lockOpenTypes } from '@/libs/const'
import dayjs from 'dayjs'
import roomUnnormal from './roomUnnormal'
import roomOperate from './roomOperate'
import roomLicens from './roomLicens'
import functionCode from './function-code'
import openapiLog from '../log/openapi-log'

export default {
  name: 'lock',
  props: {
    homeId: Number,
    deviceInfo: Object // 设备信息
  },
  created () {
    this.room = this.deviceInfo
    this.getOpenList()

    // 迁移过来门锁没有 description
    if (this.room && !this.room.description) {
      this.room.description = '门锁'
    }
  },
  components: {
    roomUnnormal,
    roomOperate,
    roomLicens,
    functionCode,
    openapiLog
  },
  data () {
    return {
      loading: false,
      loadingLog: false,
      selectedName: 'one', // 当前被激活的tab的name，初始化为第一个tab
      edit: true,
      data_slot: '1',
      lock_info: {},
      open_list: [],
      total: null,
      dataLockLog: [],
      listQuery: {
        limit: 10,
        page: 1,
        start_time: dayjs()
          .subtract(7, 'day')
          .format('YYYY-MM-DD'),
        end_time: dayjs().format('YYYY-MM-DD')
      },
      cutout: false,
      clear: false,
      recharge: false,
      restclean: false,
      lockset: false,
      partition: false,
      setting: false,
      openTypes: {
        outer_open: '外开',
        inner_open: '内开'
      },
      columnsLockLog: [
        {
          title: '授权id',
          render: (h, p) => <span>{p.row.sourceid || '-'}</span>,
          align: 'center'
        },
        {
          title: '开门类型',
          render: (h, p) => {
            const { source, eventid } = p.row
            if (eventid === 22 || eventid === 23) return <span>-</span> // 非开门事件不展示
            if (source !== undefined) return <span>{lockOpenTypes[p.row.source]}</span>
            return <span>-</span>
          },
          align: 'center'
        },
        {
          title: '开关门时间',
          key: 'time',
          align: 'center'
        },
        {
          title: '开锁人',
          render: (h, p) => <span>{p.row.source_name || '-'}</span>,
          align: 'center'
        },
        {
          title: '开关方式',
          render: (h, p) => {
            const { extra, eventid } = p.row
            if (this.openTypes[extra]) return <span>{this.openTypes[extra]}</span>
            if (eventid === 22) return <span>-</span>
            if (eventid === 23) return <span>虚掩</span>
            return <span>-</span>
          },
          align: 'center'
        }
      ],
      loadedComponent: [],
      room: {}, // 这个不是房间是门锁,
      eleLockMap: {
        open: {
          title: '确认开启电子反锁功能?',
          content: '开启成功后，门锁能正常使用电子反锁。注：版本过低的门锁无法操作'
        },
        close: {
          title: '确认关闭电子反锁功能?',
          content: '关闭后，门锁将无法反锁。注：版本过低的门锁无法操作'
        }
      },
      specificModel: '',
      versionMap: {
        app_version: '固件版本',
        hardware_version: '硬件版本',
        protocol_version: '协议版本',
        zigbee_version: 'zigbee版本',
        ble_version: '蓝牙版本',
        fp_version: '指纹芯片版本',
        media_version: 'media芯片版本',
        kernel_version: '内核版本',
        elemeter_potocol_type: '电表协议类型',
        elemeter_potocol_version: '电表协议版本',
        zigbee_router_version: 'ZB路由版本'
      }
    }
  },
  computed: {
    permissions () {
      if (localStorage.permission) {
        return JSON.parse(localStorage.permission)
      } else {
        return {}
      }
    },
    canUseEleUnlock () {
      const { room } = this
      return room && ['T3S', 'D2F', 'T3P'].includes(room.type)
      // return room && room.locker_status && (room.ele_rvslock !== undefined || room.ele_rvslock !== null);
    },
    isD3 () {
      const { sn } = this.deviceInfo
      const { device } = util.sn2model(sn)

      return device === 'D3'
    },
    openLogColumns () {
      const { room } = this
      if (room && ['T3S', 'D2S', 'T2S'].includes(room.type)) {
        return this.columnsLockLog
      }
      return this.columnsLockLog.slice(0, this.columnsLockLog.length - 1)
    },
    isD3OrT3Lock () { // 是否是D3或者T3门锁
      const { sn } = this.deviceInfo
      const { device, SpecificModel } = util.sn2model(sn)

      if (device === 'T3' || device === 'D3') {
        this.specificModel = SpecificModel
        return true
      }

      return false
    }
  },
  methods: {
    // 电子反锁
    async handleEleLock (type) {
      const isOpen = type === 'open'
      const content = isOpen ? '设置后电子反锁正常使用' : '当前门锁在公区，关闭后，门锁将无法反锁，请确认'

      this.$Modal.confirm({
        title: `确定${isOpen ? '开启' : '关闭'}电子反锁?`,
        content,
        okText: '确定',
        cancelText: '取消',
        loading: true,
        onOk: () => {
          this.eleLock(type)
        }
      })
    },
    async eleLock (operation) {
      try {
        this.setting = true
        const res = await http.req(api.lock_ele, [this.room.roomId, this.room.id], { operation })
        if (res) {
          this.$Message.success({
            content: '设置成功, 自动刷新如未改变状态, 请手动刷新',
            duration: 6
          })
          setTimeout(() => {
            this.refreshDeviceInfo(this.room)
          }, 2000)
        }
      } catch (err) {
        console.log(err)
      } finally {
        this.$Modal.remove()
        this.setting = false
      }
    },
    handleSearch: debounce(function (searchData) {
      this.refreshDeviceInfo(searchData)
    }, 500, { leading: true }),
    async refreshDeviceInfo ({ roomId, id }) {
      this.loading = true
      this.room = await http.req(api.lock_info, [roomId, id], null)
      this.loading = false
      this.room.roomId = roomId
      this.room.id = id
      this.$Message.success('刷新成功')
    },

    refreshRoomInfo () {
      refreshRoom(this.homeId, this.room.roomId)
    },

    changeTab (name) {
      // tab被修改时候调用
      if (name === 'three') {
        // 当重新进开锁记录的Tab的时候重新请求一遍数据
        this.getOpenList()
      }
      this.selectedName = name
      if (!this.loadedComponent.includes(name)) this.loadedComponent.push(name)
    },
    ok () {
      this.edit = !this.edit
      let room = this.room
      http.request(this, api.device_update, [room.roomId, room.id], { description: this.room.description }, (res, err) => {
        if (!res || err) {
          return
        }
        this.$Message.success('修改成功')
        this.refreshRoomInfo()
      })
    },
    period (d) {
      switch (d) {
        case '0':
          this.listQuery.start_time = dayjs()
            .add('days', -3)
            .format('YYYY-MM-DD')
          this.listQuery.end_time = dayjs().format('YYYY-MM-DD')
          break
        case '1':
          this.listQuery.start_time = dayjs()
            .add('days', -7)
            .format('YYYY-MM-DD')
          this.listQuery.end_time = dayjs().format('YYYY-MM-DD')
          break
        case '2':
          this.listQuery.start_time = dayjs()
            .add('days', -30)
            .format('YYYY-MM-DD')
          this.listQuery.end_time = dayjs().format('YYYY-MM-DD')
          break
        case '3':
          this.listQuery.start_time = ''
          this.listQuery.end_time = ''
          break
      }
    },

    getOpenList (page) {
      // console.log('start_time', this.listQuery.start_time);
      if (!page) {
        // 刚进入该组件时page等于1
        page = 1
      }
      let roomId = this.room.roomId
      let device_id = this.room.id
      let params = {
        offset: (page - 1) * 10, // 构造偏移量
        limit: this.listQuery.limit,
        start_time: dayjs(this.listQuery.start_time).valueOf(),
        end_time: dayjs(this.listQuery.end_time).valueOf() + 86400000
      }
      this.loadingLog = true
      http.request(this, api.lock_open_log, [roomId, device_id], params, (res, err) => {
        this.loadingLog = false
        // this.total = res.count
        if (!res || err) {
          return
        }
        let { list, count } = res
        this.total = count // 获取item的所有数目
        list.map((value, index) => {
          value.time = dayjs(value.time).format('YYYY-MM-DD HH:mm:ss')
        })
        this.dataLockLog = list
      })
    },
    remove (index) {
      this.data6.splice(index, 1)
    }
  },
  filters: {
    dateFrm: function (el) {
      if (el === -1 || !el) {
        return ' - '
      }
      return dayjs(el).format('YYYY-MM-DD HH:mm:ss')
    },
    enableEleLockStatus (input) {
      if (!input) return '无电子反锁功能或默认开启'
      if (input === 1) return '可用'
      if (input === 2) return '不可用'
    }
  }
}
</script>
<style lang='less' scoped>
@import '../../styles/common.less';
.lock {
    &-base {
        background-color: #fff;
        &-row {
            padding: 10px 0;
            &-item {
                border-right: 1px solid #bbbec4;
                &-line {
                    padding: 15px 0 5px 20px;
                    font-size: 14px;
                    color: #000000;
                }
            }
            &-action {
                padding: 9px 0 5px 20px;
                &-button {
                    width: 100px;
                    margin-right: 5px;
                }
            }
        }
    }
}
i{
    font-style: normal
}
</style>